<template>
  <div class="construction-device-log">
    <el-form :inline="true" class="search-form">
      <el-form-item label="起始时间">
        <el-date-picker
          v-model="form.startTime"
          type="datetime"
          placeholder="开始时间"
          format="yyyy/MM/dd HH:mm"
          value-format="yyyy-MM-dd HH:mm"
          :disabled-date="disabledStartDate"
          :disabled-time="disabledStartTime"
          :clearable="false"
        />
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker
          v-model="form.endTime"
          type="datetime"
          placeholder="结束时间"
          format="yyyy/MM/dd HH:mm"
          value-format="yyyy-MM-dd HH:mm"
          :disabled-date="disabledEndDate"
          :disabled-time="disabledEndTime"
          :clearable="false"
        />
      </el-form-item>
      <el-form-item class="button-group">
        <div class="flex-container">
          <el-button type="primary" @click="queryList()">查询</el-button>
        </div>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      :header-cell-style="{ background: '#F5F6F7' }"
      size="large"
    >
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="timestamp" label="时间(GMT+8)" />
      <el-table-column prop="level" label="日志级别" />
      <el-table-column prop="type" label="日志类型" />
      <el-table-column prop="message" label="日志消息" />
      <el-table-column prop="roleName" label="事件来源" />
    </el-table>

    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import minMax from 'dayjs/plugin/minMax'
dayjs.extend(minMax)

export default {
  name: 'ConstructionDeviceLog',
  data() {
    const now = dayjs()
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 100,
      loading: false,
      form: {
        endTime: now.format('YYYY-MM-DD HH:mm'),
        startTime: now.subtract(12, 'hour').format('YYYY-MM-DD HH:mm')
      }
    }
  },
  watch: {
    'form.endTime'(val) {
      const end = dayjs(val)
      const todayEnd = dayjs().endOf('day')
      if (end.isAfter(todayEnd)) {
        this.form.endTime = todayEnd.format('YYYY-MM-DD HH:mm')
      }
      const start = dayjs(this.form.startTime)
      if (start.isAfter(end) || start.isBefore(end.subtract(3, 'day'))) {
        this.form.startTime = end.subtract(12, 'hour').format('YYYY-MM-DD HH:mm')
      }
    },
    'form.startTime'(val) {
      const start = dayjs(val)
      const end = dayjs(this.form.endTime)
      const maxEnd = dayjs.min(start.add(3, 'day'), dayjs().endOf('day'))
      if (end.isBefore(start) || end.isAfter(maxEnd)) {
        this.form.endTime = start.add(12, 'hour').format('YYYY-MM-DD HH:mm')
      }
    }
  },
  mounted() {
    this.loadList()
  },
  methods: {
    loadList() {
      // 模拟接口请求，生产中替换为实际 API
      console.log('查询日志：', this.form)
      this.loading = true
      setTimeout(() => {
        this.tableData = [
          { name: '2025-06-24 12:00', username: 'MQTT', roleName: '设备上线' }
        ]
        this.total = 1
        this.loading = false
      }, 500)
    },
    updatePage(page) {
      this.currentPage = page
      this.loadList()
    },
    updateSize(size) {
      this.pageSize = size
      this.currentPage = 1
      this.loadList()
    },
    disabledStartDate(date) {
      if (!this.form.endTime) return false
      const end = dayjs(this.form.endTime)
      const todayEnd = dayjs().endOf('day')
      return (
        date.getTime() < end.subtract(3, 'day').toDate().getTime() ||
        date.getTime() > end.toDate().getTime() ||
        date.getTime() > todayEnd.toDate().getTime()
      )
    },
    disabledEndDate(date) {
      if (!this.form.startTime) return false
      const start = dayjs(this.form.startTime)
      const todayEnd = dayjs().endOf('day')
      return (
        date.getTime() < start.toDate().getTime() ||
        date.getTime() > start.add(3, 'day').toDate().getTime() ||
        date.getTime() > todayEnd.toDate().getTime()
      )
    },
    disabledStartTime() {
      const end = dayjs(this.form.endTime)
      const min = end.subtract(3, 'day')
      const max = end
      return this.getDisabledTimeRange(min, max)
    },
    disabledEndTime() {
      const start = dayjs(this.form.startTime)
      const max = dayjs().endOf('day')
      const maxLimit = dayjs.min(start.add(3, 'day'), max)
      return this.getDisabledTimeRange(start, maxLimit)
    },
    getDisabledTimeRange(min, max) {
      return {
        disabledHours: () => {
          const hours = []
          for (let i = 0; i < 24; i++) {
            const t = dayjs().hour(i).minute(0)
            if (t.isBefore(min, 'hour') || t.isAfter(max, 'hour')) hours.push(i)
          }
          return hours
        },
        disabledMinutes: (hour) => {
          const minutes = []
          for (let m = 0; m < 60; m++) {
            const t = dayjs().hour(hour).minute(m)
            if (t.isBefore(min, 'minute') || t.isAfter(max, 'minute')) minutes.push(m)
          }
          return minutes
        }
      }
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.queryList()
    },
    // 当前页变时触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.queryList()
    }
  }
}
</script>

<style scoped lang="scss">
.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
.button-group {
  margin-left: auto !important;
  min-width: max-content;
}
</style>
